package service

import (
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"gorm.io/gorm"
	"main/app"
	"main/internal/model"
	"main/internal/pkg/code"
	"main/internal/pkg/jwtoken"
	"main/internal/pkg/randstr"
	"time"
)

var SysAdminService = sysAdminService{}

// sysAdminService 业务层
type sysAdminService struct {
}

func (t sysAdminService) db() *gorm.DB {
	return app.Db
}

// Create 创建记录
func (t sysAdminService) Create(v model.SysAdmin, uid uint) (model.SysAdmin, error) {
	v.AdminExpiration = time.Now().AddDate(10, 0, 0)
	v.CreateBy = uid
	v.Status = "1"
	v.AdminPasswordSalt = randstr.GetRandStr()
	v.AdminPassword = GetPasswd(v.AdminPassword, v.AdminPasswordSalt)
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Create(&v)
	if dbres.Error != nil {
		return model.SysAdmin{}, dbres.Error
	}
	return v, nil
}

// Login 用户登录
func (t sysAdminService) Login(usermail, userpasswd, lang string) (string, error) {
	var userinfo model.SysAdmin
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Where("admin_email = ? AND status = 1", usermail).Find(&userinfo)
	if dbres.Error != nil {
		return "", dbres.Error
	}
	if dbres.RowsAffected <= 0 {
		return "", errors.New(code.GetMsg(code.RecordNotExist, lang))
	}
	if GetPasswd(userpasswd, userinfo.AdminPasswordSalt) == userinfo.AdminPassword {
		jwt, err := jwtoken.GenerateJwt(userinfo.ID, userinfo.AdminEmail, 20*time.Minute)
		if err != nil {
			return "", err
		}
		return jwt, nil
	} else {
		return "", errors.New(code.GetMsg(code.AccountOrPasswordError, lang))
	}
}

// CreateList 批量创建记录
func (t sysAdminService) CreateList(v []model.SysAdmin, uid uint) ([]model.SysAdmin, error) {
	for k, _ := range v {
		v[k].AdminExpiration = time.Now().AddDate(10, 0, 0)
		v[k].CreateBy = uid
		v[k].AdminPasswordSalt = randstr.GetRandStr()
		v[k].AdminPassword = GetPasswd(v[k].AdminPassword, v[k].AdminPasswordSalt)
		v[k].Status = "1"
	}
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Create(&v)
	if dbres.Error != nil {
		return []model.SysAdmin{}, dbres.Error
	}
	return v, nil
}

// Delete 根据ID删除记录
func (t sysAdminService) Delete(v uint, uid uint) (uint, error) {
	t.db().Table(model.SysAdmin{}.TableName()).Where("id = ?", v).Update("delete_by", uid)
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Where("id = ?", v).Delete(&v)
	if dbres.Error != nil {
		return v, dbres.Error
	}
	return v, nil
}

// DeleteList 根据ID批量删除记录
func (t sysAdminService) DeleteList(v []uint, uid uint) ([]uint, error) {
	t.db().Table(model.SysAdmin{}.TableName()).Where("id IN (?)", v).Update("delete_by", uid)
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Where("id IN (?)", v).Delete(&v)
	if dbres.Error != nil {
		return v, dbres.Error
	}
	return v, nil
}

// Get 根据ID查询
func (t sysAdminService) Get(v uint, lang string) (model.SysAdmin, error) {
	var data model.SysAdmin
	var count int64
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Where("id = ?", v).Find(&data).Count(&count)
	if count == 0 {
		err := errors.New(code.GetMsg(code.RecordNotExist, lang))
		return model.SysAdmin{}, err
	}
	if dbres.Error != nil {
		return data, dbres.Error
	}
	return data, nil
}

// GetList 批量查询
func (t sysAdminService) GetList(page, size int, kw string, ids []uint, id uint, dateForm, dateTo, status, lang string) ([]model.SysAdmin, error, int64) {
	var data []model.SysAdmin
	var count int64
	limit := size
	offset := size * (page - 1)
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Count(&count)
	dbres = t.db().Table(model.SysAdmin{}.TableName())
	if kw != "" {
		dbres = dbres.Where("admin_email LIKE ?", "%"+kw+"%")
	}
	if id != 0 {
		dbres = dbres.Where("id = ?", id)
	}
	if len(ids) > 0 {
		if ids[0] != 0 {
			dbres = dbres.Where("id IN (?)", ids)
		}
	}
	if dateForm != "" {
		dbres = dbres.Where("created_at >= ?", dateForm)
	}
	if dateTo != "" {
		dbres = dbres.Where("created_at <= ?", dateTo)
	}
	if status != "" {
		dbres = dbres.Where("status = ?", status)
	}
	if page != 0 {
		dbres = dbres.Limit(limit).Offset(offset)
	}
	dbres.Find(&data).Count(&count)
	if count == 0 {
		err := errors.New(code.GetMsg(code.RecordNotExist, lang))
		return []model.SysAdmin{}, err, count
	}
	if dbres.Error != nil {
		return data, dbres.Error, count
	}
	return data, nil, count
}

// UpdateData 根据ID更新数据
func (t sysAdminService) UpdateData(v model.SysAdmin, uid uint) (model.SysAdmin, error) {
	var data model.SysAdmin
	v.UpdateBy = uid
	dbres := t.db().Table(model.SysAdmin{}.TableName()).Save(&v)
	if dbres.Error != nil {
		return data, dbres.Error
	}
	return data, nil
}

func GetPasswd(passwd string, psswordsalt string) string {
	//开始拼接密码  密码盐值
	passwd = passwd + psswordsalt
	//获取哈希值
	hash := sha256.New()
	hash.Write([]byte(passwd))
	//计算出加密后的密码 sha256值
	passwd = hex.EncodeToString(hash.Sum(nil))
	return passwd
}
